package com.demo.villageresidence.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.villageresidence.dto.Result;
import com.demo.villageresidence.dto.UserDTO;
import com.demo.villageresidence.pojo.Admin;
import com.demo.villageresidence.pojo.User;
import com.demo.villageresidence.service.UserService;
import com.demo.villageresidence.mapper.UserMapper;
import com.demo.villageresidence.utils.JwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.HashMap;
import java.util.Map;

/**
* @author CF
* @description 针对表【tb_user】的数据库操作Service实现
* @createDate 2023-01-24 00:50:31
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Override
    public Map<String, Object> login(UserDTO userDTO) {
        // 实现登录功能
        Map<String,Object> result = new HashMap<>();
        User user = query().eq("user_phone", userDTO.getUserPhone()).one();
        if (!BCrypt.checkpw(userDTO.getUserPassword().toString(),user.getUserPassword().toString())) {
            result.put("code", 400);
            result.put("msg", "用户名或密码错误");
            result.put("token", null);
        }else{
            // 数据库中查询到有效信息生成token
            String token = JwtUtil.createTokenForUser();
            result.put("code", 200);
            result.put("msg", "登录成功");
            result.put("token", token);
            result.put("userId", user.getUserId());
            result.put("userAvatar", user.getUserAvatar());
        }
        return result;
    }

    @Override
    public Result register(User user) {
        // 对密码进行BCrypt加密
        String UserPassword = BCrypt.hashpw(user.getUserPassword());
        user.setUserPassword(UserPassword);
        user.setIsDelete(0);
        // 保存用户信息
        if (save(user)){
            return Result.ok("注册成功");
        }else {
            return Result.fail("注册失败");
        }
    }



}




